<?php

class Comment_Model extends CI_Model {

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Get list comments by nodeID
     * @param <type> $nodeID
     * @param <type> $limit
     * @param <type> $offset
     * @return <type>
     */
    public function getListCommentByNodeID($nodeID, $limit = 10, $offset = 0)
    {
        $query = 'SELECT SQL_CALC_FOUND_ROWS * FROM comments ';
        $query.= 'WHERE node_id = '. $nodeID .' ';
        $query.= 'ORDER BY cm_id DESC LIMIT '. $offset .', '. $limit;

        $result['data'] = $this->db->query($query)->result_array();

        $query = 'SELECT FOUND_ROWS() AS total';

        $total  = $this->db->query($query)->row_array('total');

        $result['total'] = $total['total'];

        return $result;
    }

    /**
     * Insert new comment
     * @param <type> $params
     * @return <type>
     */
    public function insertComment($params)
    {
        //Insert comments
        $this->db->insert('comments', $params);

        return $this->db->insert_id();
    }
    
    /**
     * Get list comments by nodeID
     * @param <type> $nodeID
     * @param <type> $limit
     * @param <type> $offset
     * @return <type>
     */
    public function getListCommentByStatus($status = 0, $limit = 10, $offset = 0)
    {
        $query = 'SELECT SQL_CALC_FOUND_ROWS cm.*, n.node_id, n.title ';
        $query.= 'FROM comments AS cm ';
        $query.= 'JOIN nodes AS n ON cm.node_id = n.node_id ';
        $query.= 'AND cm.status = '. $status .' ';
        $query.= 'ORDER BY cm_id DESC LIMIT '. $offset .', '. $limit;

        $result['data'] = $this->db->query($query)->result_array();

        $query = 'SELECT FOUND_ROWS() AS total';

        $total  = $this->db->query($query)->row_array('total');

        $result['total'] = $total['total'];

        return $result;
    }
    
    /**
     * Update comment status
     * @param type $commentID
     * @param type $status 
     */
    public function updateCommentStatus($commentID, $status)
    {
        return $this->db->update('comments', array('status' => $status), array('cm_id' => $commentID));
    }
    
    /**
     * Delete comment by $commentID
     * @param <int> $commentID
     * @return <bool>
     */
    public function deleteComment($commentID)
    {
        //Delete fields of node
        $this->db->delete('comments', array('cm_id' => $commentID));

        //Check if node is deleted and return value
        return ($this->db->affected_rows() > 0) ? true : false;
    }

}

?>